﻿using System.IO;
using System.Text.RegularExpressions;

namespace DadaLib
{
    /// <summary>
    /// Reads an input text from the file system and splits it into words
    /// </summary>
    public class FileParser
    {
        private string _fileName;
        private string[] _words;
        private int _currentWordIndex;

        public FileParser(string fileName)
        {
            this._fileName = fileName;
            var text = File.ReadAllText(fileName);
            text = Regex.Replace(text, @"\,", " ,");
            text = Regex.Replace(text, @"\.", " .");
            text = Regex.Replace(text, @"\;", " ;");
            text = Regex.Replace(text, @"\:", " :");
            text = Regex.Replace(text, "\"", " \"");
            text = Regex.Replace(text, "\'", " \'");
            text = Regex.Replace(text, @"[\r\n]", " ");
            text = Regex.Replace(text, @"[\n]", " ");
            text = Regex.Replace(text, @"[\r]", " ");
            text = Regex.Replace(text, @"   ", " ");
            text = Regex.Replace(text, @"  ", " ");
            text = Regex.Replace(text, "\\d", " ");
            text = Regex.Replace(text, "\\[", " ");
            text = Regex.Replace(text, "\\]", " ");
            _words = Regex.Split(text, @" ", RegexOptions.None | RegexOptions.Singleline);
            _currentWordIndex = 0;
        }

        /// <summary>
        /// Checks the end of file.
        /// </summary>
        /// <returns>True if there are no more words</returns>
        public bool EndOfFile()
        {
            return _currentWordIndex == _words.Length - 1;
        }

        /// <summary>
        /// Resets this instance.
        /// </summary>
        public void Reset()
        {
            _currentWordIndex = 0;
        }

        /// <summary>
        /// Gets the next word in the input file.
        /// </summary>
        /// <returns></returns>
        public string GetNextWord()
        {
            if (_currentWordIndex > _words.Length - 1)
                return null; // EOF
            var word = _words[_currentWordIndex++];
            if (word.Length == 0)
                return GetNextWord();
            return word;         
        }
    }
}
